package com.shihb.chapter05matchcase

/**
 * Description:
 *
 * @author shihb
 * @date 2020/9/30 15:41
 */
object Demo05MatchObject {
  // 单个参数
  def test1: Unit = {
    //    val d = 36.0
    val d: Double = Square(6)
    d match {
      //说明 case Square(n)得运行机制
      // 调用Square的napply(z: Double)方法，d的值就是Z
      // 返回的Some(6)也就是表示匹配成功,返回None表示匹配失败
      // 将6 赋给Square(n)的n
      case Square(n) => println(n)
      case _ => println("nothing")
    }
  }

  //多个参数
  def test2: Unit = {
    val str = "A,b,c"
    str match {
        //返回值的个数和构造器一致
      case Names(first, second, third) => println(first, second, third)
      case _ => println("nothing")
    }
  }

  def main(args: Array[String]): Unit = {
    test2

  }
}

object Square {
  /*
    说明
    unapply方法是对象提取器
    返回值是Some(math.sqrt(z)) 返回传入值得开平方
   */
  def unapply(z: Double): Option[Double] = {
    println("unapply被触发 z是" + z)
    Some(math.sqrt(z))
  }

  def apply(z: Double): Double = z * z
}

object Names {
  // 当构造器多个时调用unapplySeq
  def unapplySeq(str: String): Option[Seq[String]] = {
    println("unapplySeq被触发 " + str)
    if (str.contains(",")) Some(str.split(",")) else None
  }
}
